import requests
import json
import re
import config  # Import the configuration file

class DeepSeekAnalyzer:
    """
    A class to analyze resumes by calling the DeepSeek API.
    """
    def __init__(self):
        self.api_url = config.API_URL
        self.api_key = config.API_KEY
        self.model = config.MODEL_NAME

    def _build_optimized_prompt(self, resume_text, job_requirements):
        """
        Builds the optimized prompt for the AI model, based on the tutorial.
        """
        return f"""
你是一位有10年经验的资深HR总监,擅长快速准确地评估候选人与职位的匹配度。

【评估任务】
请根据职位要求分析候选人简历,从专业角度给出客观评估。

【职位要求】
{job_requirements}

【候选人简历】
{resume_text}

【输出要求】
必须返回标准JSON格式,不要有任何其他文字:
{{
    "skill_match": <数字(0-100)>,
    "experience_match": <数字(0-100)>,
    "education_match": <数字(0-100)>,
    "overall_score": <数字(0-100)>,
    "recommendation": "<简要推荐理由(不超过50字)>",
    "concerns": "<需要关注的问题(不超过50字)>"
}}

注意: 请客观公正地评估,避免过高或过低的分数。
"""

    def _robust_json_parse(self, response_text):
        """
        A robust method to parse JSON from the model's response,
        as described in the tutorial.
        """
        # 1. Try to find the JSON block
        match = re.search(r'\{.*\}', response_text, re.DOTALL)
        if match:
            json_str = match.group(0)
            try:
                return json.loads(json_str)
            except json.JSONDecodeError as e:
                print(f"JSON parsing failed after finding block: {e}")
                pass # Fallback to other methods

        # 2. If direct parsing fails, try regex on the original text
        try:
            skill = int(re.search(r'"skill_match":\s*(\d+)', response_text).group(1))
            exp = int(re.search(r'"experience_match":\s*(\d+)', response_text).group(1))
            edu = int(re.search(r'"education_match":\s*(\d+)', response_text).group(1))
            overall = int(re.search(r'"overall_score":\s*(\d+)', response_text).group(1))
            rec = re.search(r'"recommendation":\s*"(.*?)"', response_text).group(1)
            con = re.search(r'"concerns":\s*"(.*?)"', response_text).group(1)
            return {
                "skill_match": skill,
                "experience_match": exp,
                "education_match": edu,
                "overall_score": overall,
                "recommendation": rec,
                "concerns": con,
            }
        except Exception as e:
            print(f"Robust JSON parsing with regex failed: {e}")
            # Return a default error structure
            return {
                "skill_match": 0,
                "experience_match": 0,
                "education_match": 0,
                "overall_score": 0,
                "recommendation": "模型分析异常",
                "concerns": "未能解析模型返回的格式",
            }

    def analyze_resume(self, resume_text, job_requirements):
        """
        Analyzes the resume against job requirements using the DeepSeek API.
        """
        prompt = self._build_optimized_prompt(resume_text, job_requirements)
        
        headers = {
            'Authorization': f'Bearer {self.api_key}',
            'Content-Type': 'application/json'
        }
        
        data = {
            "model": self.model,
            "messages": [
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": prompt}
            ]
        }

        try:
            response = requests.post(self.api_url, headers=headers, json=data, timeout=120)
            print("AI API请求跟踪---------")
            print("请求URL:", self.api_url)
            print("请求头:", headers)
            print("请求数据:", json)
            response.raise_for_status()  # Raise an exception for bad status codes (4xx or 5xx)
            
            response_json = response.json()
            ai_content = response_json['choices'][0]['message']['content']
            
            return self._robust_json_parse(ai_content)

        except requests.exceptions.RequestException as e:
            print(f"API request failed: {e}")
            return {
                "skill_match": 0,
                "experience_match": 0,
                "education_match": 0,
                "overall_score": 0,
                "recommendation": "API请求失败",
                "concerns": str(e),
            }
        except (KeyError, IndexError) as e:
            print(f"Failed to parse API response structure: {e}")
            return {
                "skill_match": 0,
                "experience_match": 0,
                "education_match": 0,
                "overall_score": 0,
                "recommendation": "API响应格式错误",
                "concerns": "未能从API响应中提取有效内容",
            }